package com.epoint.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epoint.common.Result;
import com.epoint.service.BookInfoService;
import com.epoint.service.BorrowInfoService;

/**
 * Servlet implementation class BookInfoDelAction
 */
@WebServlet("/bookinfodelaction")
public class BookInfoDelAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	BookInfoService bookInfoService = new BookInfoService();
	BorrowInfoService borrowInfoService = new BorrowInfoService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookInfoDelAction() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String ids = request.getParameter("ids");
		String[] bookIds = ids.split(",");

		List<String> successDel = new ArrayList<>();
		List<String> failDel = new ArrayList<>();
		for(String bookId : bookIds) {
			
			String bookName = bookInfoService.findById(bookId).getBookName();
			if( borrowInfoService.isBorrowByBookId(bookId) > 0) {
				failDel.add(bookName);
			}else {
				bookInfoService.deleteBookInfoByBookId(bookId);
				successDel.add(bookName);
			}
		}
		// XX 删除成功；YY 存在未归还信息，无法删除
		StringBuilder msgSb = new StringBuilder();
		for(int i = 0; i < successDel.size(); i++) {
			msgSb.append(successDel.get(i) + "删除成功;");
		}
		for(int i = 0; i < failDel.size(); i++) {
			msgSb.append(failDel.get(i) + "存在未归还信息，无法删除;");
		}
		String returnCode = Result.returnCode(4,msgSb.toString());
		response.getWriter().print(returnCode);
	}

}
